layui.use(['jquery', 'layer', 'table', 'form', 'transfer'], function() {
	let $ = layui.$;
	let layer = layui.layer;
	let table = layui.table;
	let form = layui.form;
	let transfer = layui.transfer;

	//数据列表
	if (base.isInRole('user_page')) {
		loadTable()
	}

	function loadTable() {
		let loadIndex = layer.msg('加载中...', {
			icon: 16,
			shade: 0.1
		});
		table.render({
			elem: '#user-table',
			url: base.path + '/userPage',
			method: 'post',
			where: {
				token: base.getToken()
			},
			done: function(res, curr, count) {
				layer.close(loadIndex);
			},
			cols: [
				[{
						field: 'id',
						title: '序号',
						templet: function(res) {
							return res.LAY_INDEX;
						}
					},
					{
						field: 'name',
						title: '真实姓名'
					},
					{
						field: 'account',
						title: '用户账号'
					},
					{
						field: 'state',
						title: '用户状态',
						templet: function(res) {
							return res.state == 1 ? "<span style='color:#1E9FFF'>有效</span>" : "<span style='color:#FF5722'>无效</span>";
						}
					},
					{
						field: 'userRole',
						title: '用户角色'
					},
					{
						field: 'createTime',
						title: '创建时间'
					},
					{
						title: '操作',
						fixed: 'right',
						align: 'center',
						width: 200,
						templet: function(res) {
							let html = '';
							if (res.system == 0) {
								if (base.isInRole('user_del')) {
									html += "<button lay-event='del' class='layui-btn layui-btn-sm layui-bg-red'>删除</button>"
								}
								if (base.isInRole('user_update_info')) {
									html += "<button lay-event='edit' class='layui-btn layui-btn-sm layui-bg-blue'>编辑</button>"
								}
								if (base.isInRole('user_role_list')) {
									html += "<button lay-event='edit-role' class='layui-btn layui-btn-sm layui-bg-green'>分配角色</button>";
								}
							}
							return html;
						}
					}
				]
			],
			limits: [5, 10, 20],
			page: true,
		});
	}


	//查询
	$("#user-search-form .search-btn").click(function() {
		reloadData();
		return false;
	});

	//重新加载
	function reloadData() {
		let loadIndex = layer.msg('加载中...', {
			icon: 16,
			shade: 0.1
		});
		table.reload('user-table', {
			page: {
				curr: 1
			}, //从第一页开始
			where: {
				account: $("#user-search-form [name='account']").val(),
				name: $("#user-search-form [name='name']").val(),
				state: $("#user-search-form [name='state']").val(),
				token: base.getToken()
			},
			done: function(res, curr, count) {
				layer.close(loadIndex);
			},
		});
	}

	if (!base.isInRole('user_add')) {
		$('#user-add').hide();
	}

	//添加用户
	let userAddLayer;
	$('#user-add').click(function() {
		userAddLayer = layer.open({
			type: 1,
			title: '添加用户',
			area: ['400px'],
			skin: 'layer-ext-skin',
			content: $('#user-add-dialog'),
			btn: ['提交', '关闭'],
			success: function(index, layero) {
				$("#user-add-form").find("input[name='token']").val(base.getToken());
			},
			yes: function(index, layero) {
				$('#user-add-submit').click();
			}
		});
	});
	//监听form表单提交
	form.on('submit(user-add-submit)', function(data) {
		base.ajax({
			url: '/userAdd',
			data: $('#user-add-form').serialize(),
			success: function(res) {
				if (res.code == 0) {
					layer.alert('添加成功', function(index) {
						layer.close(index);
						layer.close(userAddLayer);
						table.reload('user-table');
						$('#user-add-form')[0].reset();
					});
				} else {
					layer.alert(res.msg);
				}
			}
		});
		return false;
	});

	//监听工具栏事件
	table.on('tool(user-table)', function(obj) {
		let d = obj.data;
		switch (obj.event) {
			case 'del':
				delUser(d.id, d.name);
				break;
			case 'edit':
				$("#user-edit-form").find("input[name='userId']").val(d.id);
				$("#user-edit-form").find("input[name='token']").val(base.getToken());
				$("#user-edit-form").find("input[name='name']").val(d.name);
				$("#user-edit-form").find("select[name='state']").val(d.state);
				layui.form.render('select'); //刷新select下拉框
				editUser();
				break;
			case 'edit-role':
				loadRoles(d.id);
				break;

		}
	});

	function delUser(userId, name) {
		layer.confirm("确认要删除[ " + name + " ]吗？", function(index2) {
			layer.close(index2);
			base.ajax({
				url: '/userDel',
				data: {
					'userId': userId,
					token: base.getToken()
				},
				success: function(res) {
					if (res.code == 0) {
						layer.alert('删除成功', function(index) {
							layer.close(index);
							table.reload('user-table');
						});
					} else {
						layer.alert(res.msg);
					}
				}
			});
		});
	}

	//编辑用户
	function editUser() {
		layer.open({
			type: 1,
			title: '编辑用户',
			area: ['400px'],
			skin: 'layer-ext-skin',
			content: $('#user-edit-dialog'),
			btn: ['提交', '关闭'],
			yes: function(index, layero) {
				base.ajax({
					url: '/userUpdateInfo',
					data: $('#user-edit-form').serialize(),
					success: function(res) {
						if (res.code == 0) {
							layer.alert('修改成功', function(index2) {
								layer.close(index);
								layer.close(index2);
								table.reload('user-table');
							});
						} else {
							layer.alert(res.msg);
						}
					}
				});
			}
		});
	}

	/**
	 * 加载角色
	 * @param userId
	 */
	function loadRoles(userId) {
		layer.open({
			type: 1,
			title: '设置角色',
			area: ['550px', '480px'],
			content: $('#user-role-dialog'),
			btn: ['确定', '关闭'],
			success: function() {
				base.ajax({
					url: '/userRoleList',
					data: {
						userId: userId,
						token: base.getToken()
					},
					success: function(res) {
						if (res.code == 0) {
							transfer.render({
								elem: '#user-role-list',
								title: ['未拥有的角色', '已拥有的角色'],
								showSearch: true,
								id: 'user-role-list-id',
								data: res.data.allRole,
								value: res.data.ownRole
							});
						} else {
							layer.alert(res.msg);
						}
					}
				});
			},
			yes: function(index, layero) {
				let checkedNodes = transfer.getData('user-role-list-id');
				let roleIds = [];
				for (let i in checkedNodes) {
					let o = checkedNodes[i];
					roleIds.push(o.value);
				}
				base.ajax({
					url: '/userRoleAdd',
					data: {
						userId: userId,
						roleIds: roleIds.toString(),
						token: base.getToken()
					},
					success: function(res) {
						if (res.code == 0) {
							layer.alert('加入成功', function(index2) {
								layer.close(index);
								layer.close(index2);
								table.reload('user-table');
							});
						} else {
							layer.alert(res.msg);
						}
					}
				});
			}
		});
	}

});
